/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(['N/record', 'N/render', 'N/file','N/runtime','../common/moment'], function (record, render, file,runtime,moment) {
    function beforeLoad(context) {
        if (context.type === 'view') {
            try {
                var rec = record.load({
                    type: record.Type.ITEM_FULFILLMENT,
                    id: context.newRecord.id,
                    isDynamic: true
                });
                var fulfillOrder = {};
                //编号
                fulfillOrder.tranid = rec.getValue('tranid');
                //订单号
                var orderId = rec.getValue('createdfrom');
                log.debug('orderId',orderId);
                var orderName = rec.getText('createdfrom');
                log.debug('orderName',orderName);

                if (orderName.trim().indexOf('Sales Order') != -1 || orderName.trim().indexOf('销售订单') != -1 || orderName.trim().indexOf('#SO') != -1) {
                    //加载销售订单
                    var soRec = record.load({
                        type: 'salesorder',
                        id: orderId,
                        isDynamic: true
                    });
                    fulfillOrder.orderId = soRec.getValue('tranid');
                    //单位
                    var customerId = rec.getValue('entity');
                    var cusRec = record.load({
                        type: 'customer',
                        id: customerId,
                        isDynamic: true
                    });
                    fulfillOrder.customer = cusRec.getValue('altname');
                } else if (orderName.trim().indexOf('Transfer Order') != -1 || orderName.trim().indexOf('调拨单') != -1 || orderName.trim().indexOf('#TO') != -1) {
                    //加载调拨单
                    var toRec = record.load({
                        type: 'transferorder',
                        id: orderId,
                        isDynamic: true
                    });
                    fulfillOrder.orderId = toRec.getValue('tranid');
                } else {
                    return;
                }

                //子公司
                fulfillOrder.subsidiary = rec.getText('subsidiary').trim();
                
                //发货日期
                var dateStr = rec.getText('trandate');
                var dateFormat = runtime.getCurrentUser().getPreference('DATEFORMAT');
                var date = moment(dateStr,dateFormat);
                
                fulfillOrder.date = moment(dateStr,dateFormat).format('YYYY年MM月DD日');
                //类型
                fulfillOrder.category = rec.getText('custbody_category');
                //备注
                fulfillOrder.memo = rec.getText('memo');
                //运货车号
                fulfillOrder.truckNo = rec.getText('custbody_truckno');
                //打印次数
                fulfillOrder.printTimes = rec.getText('custbody_print_times');

                var total = 0;
                var items = [];
                var count = rec.getLineCount("item");
                //给item五个五个进行分组
                var round = Math.ceil(count / 5);
                if (round > 0) {
                    for (var i = 0; i < round; i++) {
                        var sub = {};
                        var subItems = [];
                        for (var j = i * 5; j < count; j++) {
                            rec.selectLine('item',j);
                            var item = {};
                            //订单号
                            item.orderId = fulfillOrder.orderId;
                            //物料编码
                            item.itemName = rec.getCurrentSublistText('item','itemname');
                            var itemId = rec.getCurrentSublistValue('item','item');
                            item.itemId = itemId;
                            var itemRec;
                            try {
                                itemRec = record.load({
                                    type: record.Type.INVENTORY_ITEM,
                                    id: itemId,
                                    isDynamic: true
                                });

                                //规格
                                item.size = itemRec.getValue('custitem_door_width');
                            } catch(e) {
                                itemRec = record.load({
                                    type: record.Type.ASSEMBLY_ITEM,
                                    id: itemId,
                                    isDynamic: true
                                });
                                item.size = itemRec.getValue('custitem_size');
                            }
                            //SKU
                            item.sku = itemRec.getValue('custitem_child_sku');
                            //中文名称
                            item.description = itemRec.getValue('displayname');
                            //颜色
                            item.color = itemRec.getText('custitem_color');
                            //色号
                            item.colorNumber = itemRec.getText('custitem_color_number');
                            //花型
                            item.flowerType = itemRec.getText('custitem_flower_type');
                            //花型号
                            item.flowerTypeColor = itemRec.getText('custitem_flower_type_color');
                            //数量
                            item.quantity = Number(rec.getCurrentSublistValue('item','quantity'));
                            total += item.quantity;
                            //单位
                            // item.units = rec.getCurrentSublistText('item','units');
                            item.units = itemRec.getText('saleunit');
                            fulfillOrder.units = item.units;
                            //加工描述
                            item.processingDescription = rec.getCurrentSublistText('item','custcol_processingdescription');
                            //item行备注
                            item.remarks = rec.getCurrentSublistText('item','custcol_remarks');
                            subItems.push(item);
                            if (subItems.length >= 5) {
                                break;
                            }
                        }
                        while (subItems.length < 5) {
                            var item = {};
                            subItems.push(item);
                        }
                        sub.subItems = subItems;
                        items.push(sub);
                    }
                }

                fulfillOrder.items = items;
                fulfillOrder.total = total;
                log.debug('fulfillOrder',fulfillOrder);
                //调用模板文件
                var renderer = render.create();
                renderer.templateContent = file.load(1301).getContents();
                renderer.addCustomDataSource({
                    format: render.DataSource.JSON,
                    alias: 'fulfillOrder',
                    data: JSON.stringify(fulfillOrder)
                });
                var pdfFile = renderer.renderAsPdf();
                //PDF文件存放文件夹ID
                pdfFile.folder = 185;
                //PDF文件名： 'trainId' + '-' + '当前时间戳' + .pdf
                var timestamp=new Date().getTime();
                pdfFile.name = fulfillOrder.tranid + '-' + timestamp + '.pdf';
                log.debug('pdfFile',pdfFile.name);
                var fileId = pdfFile.save();
                var invalidFile = record.create({
                    type: 'customrecord_invalid_file_id'
                });
                invalidFile.setValue('custrecord_invalid_file_id', fileId);
                invalidFile.save(); 
                var File = file.load(fileId);
                var pdfurl = File.url;
                var form = context.form;
                form.addButton({
                    id: 'custpage_button',
                    label: '打印发货单',
                    functionName: "window.open('" + pdfurl + "');"
                });
            } catch (e) {
                log.error(e.name, e.message);
            }

        }
    }


    return {
        beforeLoad: beforeLoad
    };
});
